<template>
    <div class="big-box">
        <el-row :gutter="20">
            <slot name="backToPaper" v-bind:row="row">
            </slot>
            <el-col :span="4">
                <el-select v-model="searchType" placeholder="按题型搜索">
                    <el-option label="单项选择题" value="单项选择题"></el-option>
                    <el-option label="多项选择题" value="多项选择题"></el-option>
                    <el-option label="填空题" value="填空题"></el-option>
                    <el-option label="判断题" value="判断题"></el-option>
                    <el-option label="组合题" value="组合题"></el-option>
                </el-select>
            </el-col>

            <el-col :span="4">
                <el-input v-model="searchContent" placeholder="按题干搜索"></el-input>
            </el-col>
            <el-col :span="4">
                <slot name="comfirmSelect"></slot>
                <!-- v-bind:row="row" -->
            </el-col>
            <el-col :span="8">
                <!-- <el-button type="primary" @click="search">搜索</el-button> -->
                <el-button v-show="resetBtn" @click="resetSearch">重置</el-button>
                <el-button v-show="addBtn" @click="addOrEditItem({})">添加题目</el-button>
                <el-button v-show="loadBtn" @click="startCountdown">上传题库</el-button>

            </el-col>
            <!-- <el-col :span="4"> -->
                <!-- action="http://192.168.1.103:3000/exam/T_question/adds"  -->
                <!-- <el-upload :action="baseURL + `/exam/T_question/adds`" :before-upload="handleBeforeUpload"
                    :on-success="handleUploadSuccess">
                    <el-button v-show="loadBtn">上传题库</el-button>
                </el-upload> -->
            <!-- </el-col> -->
        </el-row>
        <addItem @success="handleFormSubmit" ref="addItemRef" />
        <div style="display: flex;margin-top: 15px;">
            <el-table :style="tableStyle" :data="pageData" border>
                <el-table-column width="100px" prop="id" label="ID" align="center"></el-table-column>
                <!-- <el-table-column prop="subject" label="科目"></el-table-column> -->
                <el-table-column width="100px" prop="type" label="题型" align="center"></el-table-column>
                <el-table-column width="400px" prop="questionContent" label="题干" align="center">
                    <template #default="{ row }">
                        <!-- <div class="ellipsis">{{ row.questionContent }}</div> -->
                        <div v-html="row.questionContent" class="ellipsis" align="center"></div>
                    </template>
                </el-table-column>
                <el-table-column width="150px" prop="answer" label="答案" align="center">
                    <template #default="{ row }">
                        <!-- <div class="ellipsis"> {{  row.answer }}</div> -->
                        <div v-html="row.answer" class="ellipsis" align="center"></div>
                    </template>
                </el-table-column>
                <!-- <el-table-column width="100px" prop="score" label="分数" align="center"></el-table-column> -->
                <el-table-column width="100px" prop="difficulty" label="难度" align="center"></el-table-column>
                <!-- <el-table-column width="200px" prop="createdAt" label="创建时间">
                    <template #default="{ row }">
                        {{ formatTime(row.createdAt) }}
                    </template>
                </el-table-column> -->
                <el-table-column label="操作" align="center">
                    <template #default="{ row }">
                        <slot name="editBtn" v-bind:row="row"></slot>
                        <slot name="deleteBtn" v-bind:row="row"></slot>
                        <slot name="checkBox" v-bind:row="row"></slot>

                    </template>
                </el-table-column>
            </el-table>
            <slot name="echarts"></slot>

        </div>
        <el-pagination style="width:100%" v-model:current-page="currentPage" v-model:page-size="pageSize"
            :page-sizes="[5, 10, 15, 20]" :small="false" :background="true"
            layout="total, sizes, prev, pager, next, jumper" :total="filteredData.length"
            @size-change="handleSizeChange" @current-change="handleCurrentPageChange" />
            <el-dialog
                v-model="dialogVisible"
                title="上传要求"
                width="500"
                :before-close="handleClose"
                class="dialog-footer"
            >
                <p>1.上传题库之前请确保题库中题目的标签存在，不存在的话上传题目后不显示上传的题目</p>
                <p>2.上传题库之前请确保题库中不能存在相同题目的题，如存在相同的题则上传后不显示上传的题目</p>
                <p>3.上传题库之前请确保题库中的科目存在，如果该科目不存在则需要创建该科目才能显示题目</p>
                <template #footer>
                <div style="display: flex;">
                    <el-button @click="handleClose" style="margin-right: 10px;">取消</el-button>
                    <!-- <el-button type="primary" @click="dialogVisible = false">
                    Confirm
                    </el-button> -->
                    <el-upload :action="baseURL + `/exam/T_question/adds`" :before-upload="handleBeforeUpload"
                        :on-success="handleUploadSuccess">
                        <el-button v-show="loadBtn" :disabled="ifUpload">{{ ifUpload ? `请等待${countdownText}秒` : '继续上传'}}</el-button>
                    </el-upload>
                </div>
                </template>
            </el-dialog>
    </div>
</template>
<script setup>
import { ref, reactive, onMounted, computed, toRef, watch, onBeforeUnmount } from 'vue';
import { getTotalTitle, getSubjectTitle } from '@/api/questionBank';
import { ElMessage, ElMessageBox } from 'element-plus'
import { getIdSubject } from "@/api/subject.js"
import { useRoute } from 'vue-router';
import { formatTime } from '@/utils/format'
import { baseURL } from '@/utils/request';
import addItem from '@/views/itemBank/addItem.vue'
import { useRouter } from 'vue-router';
import { useUserStore, useClassStore } from '@/stores/index'
import { getAllExamineContent } from '@/api/tag.js'
////
const subInfo = reactive({
    syllabusId:0,
    subId:0,//可以根据路由拿到
    class_name:'',
    grade_name:'',
    subject:'',
  })
//一进入页面，则把该班级的大纲id给页面
const classMessage = useClassStore()
// syllabusId.value = classMessage.classInfo.id
subInfo.syllabusId = classMessage.classInfo.user_and_acs_id//大纲id
subInfo.class_name = classMessage.classInfo.class_name
subInfo.grade_name = classMessage.classInfo.grade_name
subInfo.subject = classMessage.classInfo.subject
subInfo.subId = classMessage.classInfo.subId

const router = useRouter()
import { useSubjectStore } from '@/stores/index'
const SubjectStore = useSubjectStore()
////
const BackToSubject = () => {
    // console.log(subject.id, '741');
    SubjectStore.toggleISInSubject()
    router.push('/')
}
const props = defineProps({
    dataArr: {
        type: Array,
        default: () => []
    },
    addBtn: {
        type: Boolean,
    },
    loadBtn: {
        type: Boolean,
    },
    resetBtn: {
        type: Boolean,
    },
})

const dataArr = ref(props.dataArr)
const searchId = ref('');
const searchSubject = ref('');
const searchType = ref('');
const searchContent = ref('');
const pageSize = ref(20);//初始化页面时题目的数量
const currentPage = ref(1);
const addItemRef = ref()

const filteredData = computed(() => {
    let data = [...dataArr.value];
    if (searchId.value) {
        data = data.filter(item => item.id.includes(searchId.value));
    }
    if (searchSubject.value) {
        data = data.filter(item => item.subject.includes(searchSubject.value));
    }
    if (searchType.value) {
        data = data.filter(item => item.type.includes(searchType.value));
    }
    if (searchContent.value) {
        data = data.filter(item => item.questionContent.includes(searchContent.value));
    }
    console.log(data,'data1');
    return data;
});


const pageData = computed(() => {
    // const startIndex = (currentPage.value - 1) * pageSize.value;
    // return filteredData.value.slice(startIndex, startIndex + pageSize.value);
    //根据id由高到低
    const startIndex = (currentPage.value - 1) * pageSize.value;
    const sortedData = filteredData.value.slice().sort((a, b) => b.id - a.id);
    return sortedData.slice(startIndex, startIndex + pageSize.value);
});

const handleCurrentPageChange = (page) => {
    currentPage.value = page;
}

const handleSizeChange = (val) => {
    pageSize.value = val;
}

//重置
const resetSearch = () => {
    searchId.value = ''
    searchSubject.value = ''
    searchType.value = ''
    searchContent.value = ''
}

//对话框
const dialogVisible = ref(false)

//关闭对话框
const handleClose = () => {
    dialogVisible.value = false
    countdownText.value = 5
}

//判断是否可以上传
const ifUpload = ref(true);
//倒计时的时间
const countdownText = ref(5);

//打开对话框
const startCountdown = () => {
    dialogVisible.value = true
    countdownText.value = 5
    ifUpload.value = true;

  const interval = setInterval(() => {

    countdownText.value--
    if (countdownText.value <= 0) {
      clearInterval(interval);
      ifUpload.value = false;
    }
    //判断对话框是否关闭，关闭后则清除计时器
    if(dialogVisible.value === false) {
        countdownText.value = 5
        clearInterval(interval);
    }
  }, 1000);
}

// 文件
const handleBeforeUpload = (file) => {
    //对文件增加限制大小，文件的类型等操作
    console.log(file, 'file');

    //让文件只能上传.xlsx文件
    const allowedFileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
    if (file.type !== allowedFileType) {
        ElMessage.error('只能上传 .xlsx 文件');
        return false; // 取消文件上传
    }

    return true; // 允许文件上传
}

const handleUploadSuccess = async (res, file) => {
    console.log(res, 'file的数据');
    // console.log( '上传成功',res,file);
    if(res.code === 203){
        ElMessage.error(`${res.msg}或检查是否按要求填写文件`);
        handleClose()
        return
    }

    const responseData = res.data

    console.log(res, 'file的数据');
    responseData.forEach((response) => {
        const questionData = {
            id: response.id,
            type: response.type,
            questionContent: response.questionContent,
            answer: response.answer,
            score: response.score,
            difficulty: response.difficulty,
            createdAt: response.createdAt,
            options: response.options,
            // subject: response.subject
            sub_id: response.sub_id
        }
        if (questionData.sub_id === subInfo.subId)
            dataArr.value.push(questionData)
        // console.log(dataArr,'dataArr');
        // console.log(dataArr.value,'dataArr.value');
    })
    // }else ElMessage.error(`上传文件里的科目和该科目不一致,已导入${responseData.subject}科目`);
    ElMessage.success('上传成功')
    handleClose()
}

// 添加题
const addOrEditItem = async (row) => {
    //获取有没有标签，没有标签则不可以添加题目
    const res = await getAllExamineContent(subInfo.subId)
    if(res.data.data.length === 0){
        ElMessageBox.alert('请先在标签管理页面上添加标签后再添加题目', '提示', {
        confirmButtonText: '确定',
        });
        return 
    }
    console.log('addItem triggered');
    addItemRef.value.open(row)
}

// 处理表单提交，添加成功后更新数据
const handleFormSubmit = (data) => {
    dataArr.value.push(data)
}


const route = useRoute()
//传过来的id为string，将他变为int
let num = parseInt(route.params.subId)

//获取到科目全部题
const getTitle = async () => {
    // const res = await getSubjectTitle()
    const res = await getTotalTitle(num)
    // const res = await getTotalTitle(1)
    //获取当前页面科目
    const res1 = await getIdSubject(route.params.subId)
    // const res1 = await getIdSubject(1)
    const res1Data = res1.data.data

    console.log(res, 'resssss');
    const responseData = res.data.data
    // console.log( res.data.data);
    // console.log(res,'66666');
    responseData.forEach((response) => {
        const questionData = {
            id: response.id,
            type: response.type,
            questionContent: response.questionContent,
            answer: response.answer,
            score: response.score,
            difficulty: response.difficulty,
            createdAt: response.createdAt,
            options: response.options,
            subject: res1Data.subject
        }
        dataArr.value.push(questionData)
    })
    //   console.log(dataArr,'dataaAarr');
    console.log(props.dataArr, '传过组件的值');


}
const isRefresh = ref(true)
const emit = defineEmits(['success']);

// 监测窗口大小并设置表格宽度比例
const windowWidth = ref(window.innerWidth);

const updateWindowWidth = () => {
    windowWidth.value = window.innerWidth;
};

// 当窗口大小发生变化时，更新 `windowWidth`
window.addEventListener('resize', updateWindowWidth);

onBeforeUnmount(() => {
    window.removeEventListener('resize', updateWindowWidth);
});

// 根据窗口大小设置表格宽度比例
const tableStyle = computed(() => {
    if (windowWidth.value >= 400 && windowWidth.value < 600) {
        return {
            width: '100%', // 窗口宽度小于 600px 时，表格宽度设置为 100%
        };
    } else if (windowWidth.value >= 600 && windowWidth.value < 900) {
        return {
            width: '100%', // 窗口宽度在 600px 到 900px 之间时，表格宽度设置为 80%
        };
    } else {
        return {
            width: '100%', // 窗口宽度大于 900px 时，表格宽度设置为 60%
        };
    }
});

onMounted(() => {
    if (isRefresh.value) {
        getTitle()
        isRefresh.value = false
        emit('Refresh', isRefresh)
    } else emit('Refresh', isRefresh)
})
</script>

<style>
.el-pagination {
    display: flex;
    margin-top: 20px;
    /* margin: 20px auto; */
    justify-content: center;
}

.ellipsis {
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.big-box {
    width: 100%;
}

.dialog-footer p{
    /* line-height: 16px; */
    font-size: 16px;
    height: 50px;
    /* color: aqua; */
}

/* //去除上传成功后的进度显示条 */
.el-upload-list--text{
    display: none;
  }
</style>